package com.nmgydy.util;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.nmgydy.beans.CacheBean;

public class CacheUtil {
	
	private static final Map<String,CacheBean> cacheMap;
	
	static{
		cacheMap = new ConcurrentHashMap<String, CacheBean>();
	}
	
	public static void put(String key,Object value){
		cacheMap.put(key,new CacheBean(value,0L));
	}
	
	public static void put(String key,Object value,long expireTime){
		cacheMap.put(key,new CacheBean(value,new Date().getTime()+expireTime*1000));
	}
	
	public static Object get(String key){
		CacheBean bean = cacheMap.get(key);
		if(bean == null){
			return null;
		}else{
			long expireTime = bean.getExpireTime();
			//未过期
			if(expireTime <= 0 || expireTime - new Date().getTime() > 0){
				return bean.getData();
			}else{
				cacheMap.remove(key);
				return null;
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		CacheUtil.put("key", "123",3);
		Thread.sleep(1000L);
		System.out.println(CacheUtil.get("key"));
		Thread.sleep(3000L);
		System.out.println(CacheUtil.get("key"));
	}
}
